<template>
  <div class="app-container">
    <div class="search-container">
      <el-form :model="searchParam" :inline="true" label-width="63px">
        <el-form-item label="发放日期">
          <el-date-picker
            v-model="searchParam.grantDateSearch"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD HH:mm:ss"
            @change="getgrantDate"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="领用部门">
          <SelectOriganizationDangerGrant
            @change="(ids:string) => getSelectIds(ids, '领用部门')"
            :isCheckStrictly="true"
            :isMultiple="false"
            :disabled="false"
            :data="dataObject('领用部门')"
            :selectData="searchParam.receiveDepartmentId"
          />
        </el-form-item>
        <el-form-item label="领用人">
          <el-select
            v-model="searchParam.receivePersonId"
            placeholder="请选择领用人"
            clearable
          >
            <el-option
              v-for="item in personList"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="search"
            ><i-ep-search />搜索</el-button
          >
          <el-button @click="reset"><i-ep-refresh />重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never" class="table-container">
      <template #header>
        <el-button type="success" plain @click="openDialog()"
          ><i-ep-plus />新增</el-button
        >
        <el-button
          type="danger"
          plain
          :disabled="ids.length === 0"
          @click="handleTableDelete()"
          ><i-ep-delete />删除</el-button
        >

        <el-button
          type="primary"
          @click="handleAuti()"
          :disabled="ids.length === 0"
          >审核</el-button
        >
      </template>

      <el-table
        ref="dataTableRef"
        v-loading="loading"
        :data="tableData"
        highlight-current-row
        border
        @selection-change="handleSelectionChange"
        @sort-change="onTableSortChanged"
      >
        <el-table-column
          type="selection"
          width="55"
          align="center"
          :selectable="selected"
        >
        </el-table-column>
        <el-table-column
          label="单据号"
          prop="recordCode"
          min-width="120"
          show-overflow-tooltip
          sortable
        >
        </el-table-column>
        <el-table-column
          label="原始凭证号"
          prop="originalVoucherNo"
          min-width="120"
          show-overflow-tooltip
          sortable
        >
        </el-table-column>

        <el-table-column
          label="发放日期"
          prop="grantDate"
          min-width="180"
          show-overflow-tooltip
          align="center"
          sortable
        >
          <template #default="scope">
            {{ dayjs(scope.row.grantDate).format("YYYY-MM-DD") }}
          </template>
        </el-table-column>

        <el-table-column
          label="发放原因"
          prop="grantReason"
          min-width="100"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column
          label="发放人"
          prop="grantPersonName"
          min-width="120"
          show-overflow-tooltip
          align="center"
          sortable
        >
        </el-table-column>
        <el-table-column
          label="领用部门"
          prop="receiveDepartmentName"
          min-width="180"
          show-overflow-tooltip
          sortable
        >
        </el-table-column>
        <el-table-column
          label="领用人"
          prop="receivePersonName"
          min-width="120"
          show-overflow-tooltip
          align="center"
          sortable
        >
        </el-table-column>
        <el-table-column
          label="是否审核"
          prop="isAudit"
          min-width="120"
          align="center"
          sortable
        >
          <template #default="scope">
            <el-tag type="success" v-if="scope.row.isAudit === 1">是</el-tag>
            <el-tag type="info" v-else>否</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          label="备注"
          prop="remarks"
          min-width="100"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="240">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              link
              @click="openDialogdetail(scope.row)"
              ><i-ep-search />
              查看
            </el-button>
            <el-button
              type="primary"
              size="small"
              link
              :disabled="scope.row.isAudit === 1"
              @click="openDialog(scope.row)"
              ><i-ep-edit />编辑</el-button
            >
            <el-button
              type="primary"
              size="small"
              link
              :disabled="scope.row.isAudit === 1"
              @click="deleteItem(scope.row.id)"
              ><i-ep-delete />删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        :background="true"
        :current-page="pageable.pageNum"
        :page-size="pageable.pageSize"
        :page-sizes="[10, 25, 50, 100]"
        :total="pageable.total"
        layout="total, sizes, prev, pager, next, jumper"
        class="mt-[20px]"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <eamgrantrecord-edit
      :visible="addDialog.visible"
      :title="addDialog.title"
      :data="addDialog.data"
      @reset-table="(id:string) => (id?.length ? getTableList() : reset())"
      :is-readonly="addDialog.readvisible"
      @change-visible="changeVisible"
    />
  </div>
</template>

<script setup lang="ts">
import { useTable, useDictionary } from "@/utils/useTable";
import request from "@/utils/request";
import dayjs from "dayjs";
import { filterOrder } from "@/utils/commonHooks";
defineOptions({
  name: "EAMEAMGRANTRECORD",
  inheritAttrs: false,
});

// 请求参数
const requestApi = "/eam/mtgrantrecord/queryByPage";

// 是否需要分页
const pagination = true;

const initParam = reactive({
  sort: {
    column: "",
    orderBy: "",
  },
});

// 初始化搜索参数数据
const searchParamInit = {
  recordCode: "",
  originalVoucherNo: "",
  assetKind: "",
  grantDateSearch: [],
  grantDateStart: "",
  grantDateEnd: "",
  grantPersonId: "",
  grantPersonName: "",
  receiveDepartmentId: "",
  receiveDepartmentName: "",
  receivePersonId: "",
  receivePersonName: "",
  isAudit: "",
  deleted: "",
  organizationId: "",
  createTimeSearch: [],
  createTimeStart: "",
  createTimeEnd: "",
  lastUpdateTimeSearch: [],
  lastUpdateTimeStart: "",
  lastUpdateTimeEnd: "",
};

const deleteParam = {
  api: "/eam/mtgrantrecord/delete",
  data: {},
};

// 数据请求错误后处理
function requestError() {}

const dataCallBack = ref(undefined); // 无需二次数据处理&不传赞数也行

// 表格操作 Hooks
const {
  tableData,
  pageable,
  searchParam,
  ids,
  getTableList,
  search,
  reset,
  handleSizeChange,
  handleCurrentChange,
  handleSelectionChange,
  handleTableDelete,
  loading,
}: any = useTable(
  requestApi,
  initParam,
  searchParamInit,
  pagination,
  dataCallBack.value,
  requestError,
  deleteParam
);

onMounted(() => {
  getTableList();
});
// 排序
// 监听表格排序方法
function onTableSortChanged(column: any) {
  const { prop, order } = column;
  console.log(prop, order);

  initParam.sort = {
    column: prop,
    orderBy: filterOrder(order),
  };
}
// 监听页面 initParam 改化，重新获取表格数据
watch(() => initParam, getTableList, { deep: true });
const addDialog = reactive<DialogOption>({
  visible: false,
  readvisible: false,
  title: "",
  data: {},
});

// 查询详情
async function getInfo(id: string) {
  request({
    url: `/eam/mtgrantrecord/get/${id}`,
    method: "get",
  })
    .then((data) => {
      addDialog.data = data.data;
      addDialog.visible = true;
    })
    .catch((res) => {
      console.log(res);
    });
}

/** 打开发放记录表单弹窗 */
function openDialog(roleObj?: Object) {
  if (roleObj) {
    addDialog.title = "修改发放记录";
    getInfo(roleObj.id);
  } else {
    addDialog.title = "新增发放记录";
    addDialog.visible = true;
  }
  addDialog.readvisible = false;
}
/** 打开发放记录表单弹窗 详情 */
function openDialogdetail(roleObj?: any) {
  addDialog.title = "发放记录详情";
  getInfo(roleObj.id);
  addDialog.readvisible = true;
}

function changeVisible(value: boolean) {
  addDialog.visible = value;
  if (!value) {
    addDialog.data = {};
  }
}

function getgrantDate(data: any) {
  if (data) {
    searchParam.value.grantDateStart = data[0];
    searchParam.value.grantDateEnd = data[1];
  } else {
    searchParam.value.grantDateStart = "";
    searchParam.value.grantDateEnd = "";
  }
}

async function deleteItem(id: any) {
  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    const { data } = await request({
      url: `/eam/mtgrantrecord/deleteItem/${id}`,
      method: "post",
    });
    search();
  });
}
/** 选择组织机构并赋值id  start **/
function getSelectIds(ids: [] | string, item: string) {
  if (item == "领用部门") {
    searchParam.value.receiveDepartmentId = ids;
    personList.value = [];
    changeDept(ids, item);
  }
}
const dataObject = (item: string) => {
  return {
    name: item == "领用部门" ? "领用部门" : "管理部门",
    defaultProps: {
      children: "nodes",
      label: "organizationName",
      value: "id",
    },
    api: "/system/sysOrganization/getUsableTree",
  };
};

// 点击组织机构 选择人员
const personList = ref([]);
const personList1 = ref([]);
const changeDept = async (id, name) => {
  if (id) {
    const res = await request({
      url: "/system/sysUser/getList ",
      method: "post",
      data: {
        departmentId: id,
      },
    });
    if (name == "领用部门") {
      personList.value = res.data;
      personList.value.map((item: any) => {
        item.label = `${item.firstName}`;
        item.value = `${item.id}`;
      });
    }
  }
};
// 批量审核
const handleAuti = () => {
  console.log(ids);

  ElMessageBox.confirm("确认审核已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    await request({
      url: `/eam/mtgrantrecord/examine`,
      method: "post",
      data: { ids: ids.value },
    });
    ElMessage.success("审核成功");
    search();
  });
};

// 审核过滤
const selected = (row, index) => {
  if (row.isAudit == 1) {
    return false; //不可勾选
  } else {
    return true; //可勾选
  }
};
</script>
